package ru.picman;

import java.util.List;
import java.util.Random;

import ru.picman.ui.PicmanView;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
/**
 * This is the Main-class. Extending Activity, this class will be the
 * class that is to be used to start the application. This class handles
 * all the events, like startup, pause, quit and it also initializes
 * the game.
 * 
 * @author Matthijs
 */
public class PicmanGame
             extends Activity implements OnTouchListener
{
	
	/**
	 * Called when the activity is first created. The game loop is started,
	 * meaning that the playing of the game is beginning. Later on, this
	 * should be done by the menu, if the user chooses 'Play'.
	 */
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.picman_game);
		
		
		init();
		
		gameloop.start();
	}
	
	/**
	 * Initializes the game. The view is created, the world is created, the
	 * bird and pigs are created and put in the world. The onTouchListener for
	 * the screen-encompassing invisible button used for touch input is set, and
	 * the SensorListeners needed for tilt-input are registered.
	 */
	private void init() {
		picmanView = (PicmanView)findViewById(R.id.picman);
		
		world = new World(this);
		
		Bird bird = new Bird();
		bird.setPosition(1,1);
		world.addEntity(bird);
		
		player = new Player("Matt",bird);
		world.setPlayer(player);
		picmanView.addKeyListener(player);
		
		
		bird.setPlayer(player);
	
		
		if(PicmanOptions.controls.equals("Trackpad"))
			controlMode = 0;
		
		else if(PicmanOptions.controls.equals("Touchscreen"))
			controlMode = 1;
		
		else if(PicmanOptions.controls.equals("Tilt"))
			controlMode = 2;
		
		Button button = (Button)findViewById(R.id.button_invisible);
		button.setOnTouchListener(this);
		
		PicmanOrientationHandler p = new PicmanOrientationHandler(player);
		
		if(controlMode == 2)
		{
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
			List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ALL);
			
			for(int i = 0; i < sensors.size(); i++)
			{
				if(sensors.get(i).getType() == Sensor.TYPE_ACCELEROMETER || 
				   sensors.get(i).getType() == Sensor.TYPE_MAGNETIC_FIELD||
				   sensors.get(i).getType() == Sensor.TYPE_ORIENTATION)
				sm.registerListener(p, sensors.get(i), SensorManager.SENSOR_DELAY_GAME);
			}
		}
		
		levelComplete();
		
		
		playing = true;
	}
	
	/**
	 * Called when all the eggs in a level have been gathered. Loads the next level, or,
	 * when no levels are left, callse @link#gameOver().
	 */
	public void levelComplete() {
		switch (PicmanLevels.level) {
			case 1:
				world.loadLevel(picmanView.getResources().getStringArray(R.array.level1));
				break;
			case 2:
				world.loadLevel(picmanView.getResources().getStringArray(R.array.level2));
				break;
			case 3:
				world.loadLevel(picmanView.getResources().getStringArray(R.array.level3));
				break;
			case 4:
				world.loadLevel(picmanView.getResources().getStringArray(R.array.level4));
				break;
			default: // End game
				gameOver();
		}
		++PicmanLevels.level;
	}
	
	/**
	 * The game is over.
	 */
	public void gameOver() {
		playing = false;
		setContentView(R.layout.picman_gameover);
		TextView scoreView = null;
		scoreView = (TextView)findViewById(R.id.gameover_score_value);
		scoreView.setText(String.valueOf(world.getPlayer().getScore()));
		
		ImageView screen = (ImageView)findViewById(R.id.gameover_image);
		screen.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	/**
	 * Returns the GameLoop of this game.
	 * 
	 * @return The GameLoop
	 */
	public GameLoop getGameLoop() {
		return gameloop;
	}
	
	/**
	 * Returns the View of this game.
	 * 
	 * @return The PicmanView
	 */
	public PicmanView getView() {
		return picmanView;
	}
	
	/**
	 * Ticks. This method is called by the GameLoop every loop. This method
	 * 'passes' the tick to the world and invalidates the view. This means
	 * that there can be drawn on the canvas (of the view).
	 */
	public void tick() {
		if (playing)
			world.tick();
		picmanView.invalidate();
	}
	
	//
	
	private World              world;
	private Player 			   player;
	private PicmanView         picmanView;
	private boolean            playing;
	
	private final GameLoop     gameloop = new GameLoop(this);
	
	public static final Random RAND     = new Random();
	public static final String TAG      = "Picman";
	
	private int CONTROL_TRACKPAD 	= 0;
	private int CONTROL_TOUCHPAD 	= 1;
	private int CONTROL_TILT 		= 2;
	
	private int controlMode = 1;
	
	
	public boolean onTouch(View v, MotionEvent event) 
	{
		if(controlMode == 1)
		{
			float x = event.getX();
			float y = event.getY();
			
			int width = picmanView.getWidth();
			int height = picmanView.getHeight();
			
			float step = Math.abs((float)height / (float)width);
			
			// Bottom-right corner of the screen
			if(x > width / 2 && y > height / 2)
			{
		
				if((y - (height / 2)) > (x - (width / 2)) * step)
					player.getUnit().setDesiredDirection(Unit.DIRECTION_DOWN);
					
				else
					player.getUnit().setDesiredDirection(Unit.DIRECTION_RIGHT);
	
				return true;
			}
			
			// Top-right corner
			else if(x > width / 2 && y <= height / 2)
			{
				if(y < (width / 2 - (x - width / 2)) * step)
					player.getUnit().setDesiredDirection(Unit.DIRECTION_UP);
					
				else
					player.getUnit().setDesiredDirection(Unit.DIRECTION_RIGHT);
				
				return true;
			}
			
			// Bottom-left corner
			else if(x <= width / 2 && y > height / 2)
			{
				if((height /2 ) - (y - (height / 2)) < x * step)
					player.getUnit().setDesiredDirection(Unit.DIRECTION_DOWN);
				
				else
					player.getUnit().setDesiredDirection(Unit.DIRECTION_LEFT);
				
				return true;
			}
			
			// Top-left corner
			if(x <= width / 2 && y < height / 2)
			{
				if(y < x * step)
					player.getUnit().setDesiredDirection(Unit.DIRECTION_UP);
				
				else
					player.getUnit().setDesiredDirection(Unit.DIRECTION_LEFT);
				
				return true;
			}
		}
		
		/*
		switch(v.getId())
		{
		case R.id.button_up:
			player.getUnit().setDesiredDirection(Unit.DIRECTION_UP);
			return true;
			
		case R.id.button_right:
			player.getUnit().setDesiredDirection(Unit.DIRECTION_RIGHT);
			return true;
			
		case R.id.button_down:
			player.getUnit().setDesiredDirection(Unit.DIRECTION_DOWN);
			return true;
			
		case R.id.button_left:
			player.getUnit().setDesiredDirection(Unit.DIRECTION_LEFT);
			return true;
		}
		*/
		return false;
		
	}
	

}